#include "DBHelper.h"
#include <string.h>

//连接
bool DBHelper::ConnectDatabase()
{
    mysql_init(&mysql);
    const char host[] = "localhost";//地址
    const char user[] = "root";//用户名
    const char passwd[] = "root";//密码
    const char db[] = "test";//数据库
    unsigned int port = 3307;//端口
    if (mysql_real_connect(&mysql, host, user, passwd, db, port, 0, 0)) {
        //printf("The connection was successful.\n");
        return true;
    }
    else {
        //printf("Error connecting to database:%s\n", mysql_error(&mysql));
        return false;
    }
	
}
//释放
void DBHelper::FreeConnect()
{
    mysql_free_result(res);
    mysql_close(&mysql);
   // cout << "释放完毕" << endl;
}
//查询
bool DBHelper::QueryDatabase(string name, string paw)
{
    string qu = "select * from users where user='"+ name + "' and password='" + paw+"';";
    //将数据格式化输出到字符串
    strcpy(query, qu.c_str());
    /*for (int i = 0; i < qu.length(); i++)
        cout << query[i];*/

    //mysql_query（）执行成功返回0
    if (mysql_query(&mysql, query)) {
        return false;
    }
    /* else {
     printf("query success\n");
    }*/


    res = mysql_store_result(&mysql);
    if (!res) {
        //printf("Couldn't get result from %s\n", mysql_error(&mysql));
        return false;
    }
    //printf("number of dataline returned: %d\n", mysql_affected_rows(&mysql));
    if (mysql_affected_rows(&mysql)==0)
    {
        return false;
    }
    
    return true;


}
//添加
bool DBHelper::InsertData(string sno,string username,string userpassword,string email)
{
    string qu = "INSERT INTO users VALUES ('" + sno + "', '" + username + "', '" + userpassword + "', '" + email + "')";
    strcpy(query, qu.c_str());
    try {
        if (mysql_query(&mysql, query)) {
            //printf("Query failed (%s)\n", mysql_error(&mysql));
            return false;
        }
        else {
            //printf("Insert success\n");
            return true;
        }
    }
    catch(exception e){
        return false;
    }
   
	
}
